package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.datasource.DynamicDataSource;
import com.ruoyi.system.service.ISysDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: youguoen
 * Date: 2024/1/3
 */
@RestController
@RequestMapping("/datasource")
public class SysDataSourceController {

    @Autowired
    private ISysDataSourceService dataSourceService;
    /**
     * 获取数据源
     * @return
     */
    @GetMapping("/list")
    public AjaxResult getDataSourceList(){
        DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
        Map<Object, DataSource> map = dynamicDataSource.getResolvedDataSources();
        List<Object> list = new ArrayList<>();
        for(Map.Entry<Object,DataSource> entry:map.entrySet()){
            list.add(entry.getKey());
        }
        return AjaxResult.success(list);
    }

    /**
     * 获取字段列表
     * @param tableName
     * @param dataSource
     * @return
     */
    @GetMapping("/getTableFields")
    public AjaxResult getTableFields(String tableName,String dataSource){
        if("CK".equals(dataSource)){
            return AjaxResult.success(dataSourceService.queryFieldsForCK(tableName,dataSource));
        }else{
            return AjaxResult.success(dataSourceService.queryFieldsForMysql(tableName,dataSource));
        }

    }
}
